package com.lambkit.solon;

import com.zaxxer.hikari.HikariDataSource;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Condition;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.BeanWrap;
import org.noear.solon.core.Props;

import javax.sql.DataSource;

/**
 * @author yangyong(孤竹行)
 */
@Configuration
public class DataSourceConfig {

    @Bean
    @Condition(onProperty="${lambkit.datasource}")
    public void dataSourceInit(@Inject("${lambkit.datasource}") String ds) {
        String[] dsNames = ds.split(",");

        for (String dsName : dsNames) {
            Props props = Solon.cfg().getProp("lambkit.db-" + dsName);

            if (props.size() > 0) {
                //按需创建数据源
                DataSource db1 = props.toBean("", HikariDataSource.class);
                //手动推到容器内
                BeanWrap bw = Solon.context().wrap(DataSource.class, db1);
                //以名字注册
                Solon.context().putWrap(dsName, bw);
                //以类型注册
                Solon.context().putWrap(DataSource.class, bw);
            }
        }
    }

}
